

// 递归创建书签节点
function createBookmarkElement(bookmark) {
  const element = document.createElement('div');
  
  // 如果是文件夹
  if (bookmark.children && bookmark.children.length > 0) {
    element.className = 'bookmark-folder';
    
    const folderName = document.createElement('div');
    folderName.className = 'folder-name';
    folderName.textContent = bookmark.title || '未命名文件夹';
    
    // 点击文件夹可以展开/折叠
    folderName.addEventListener('click', () => {
      folderName.classList.toggle('open');
      childrenContainer.style.display = folderName.classList.contains('open') ? 'block' : 'none';
    });
    
    element.appendChild(folderName);
    
    const childrenContainer = document.createElement('div');
    childrenContainer.style.display = 'block'; // 默认折叠
    
    // 递归添加子书签
    bookmark.children.forEach(child => {
      const childElement = createBookmarkElement(child);
      childrenContainer.appendChild(childElement);
    });
    
    element.appendChild(childrenContainer);
  } 
  // 如果是书签
  else if (bookmark.url) {
    const link = document.createElement('a');
    link.className = 'bookmark-item';
    link.href = bookmark.url;
    link.textContent = bookmark.title || bookmark.url;
    link.target = '_blank'; // 在新标签页打开
    element.appendChild(link);
  }
  
  return element;
}

// 获取所有书签并显示
function loadBookmarks() {
  const container = document.getElementById('bookmarks-container');
  
  chrome.bookmarks.getTree((bookmarkTreeNodes) => {
    // 清空加载提示
    container.innerHTML = '';
    // 处理每个书签节点
    bookmarkTreeNodes.forEach(node => {
      const element = createBookmarkElement(node);
      container.appendChild(element);
    });
    
    // 默认展开第一个文件夹（通常是"其他书签"）
    const firstFolder = document.querySelector('.folder-name');
    if (firstFolder) {
      firstFolder.click();
    }
  });
}

// 页面加载完成后获取书签
document.addEventListener('DOMContentLoaded', loadBookmarks);
    